package com.lamer.console.common.config;

import com.lamer.console.common.component.JwtAuthenticationTokenFilter;
import com.lamer.console.common.handle.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * extend Spring Security config
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private SecurityAuthenticationSuccessHandler securityAuthenticationSuccessHandler;

    @Autowired
    private SecurityAuthenticationFailureHandler securityAuthenticationFailureHandler;

    @Autowired
    private SecurityLogoutSuccessHandler securityLogoutSuccessHandler;

    @Autowired
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;

    @Autowired
    private SecurityAuthenticationEntryPoint securityAuthenticationEntryPoint;

    @Autowired
    private IgnoreUrlsConfig ignoreUrlsConfig;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter() {
        return new JwtAuthenticationTokenFilter();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        //java 8 is supported toArray(String[]::new) but it will show me a warn message.
        @SuppressWarnings("SimplifyStreamApiCallChains") String[] ignoreUrls = ignoreUrlsConfig.getUrls().stream().toArray(String[]::new);
        httpSecurity.cors() // open cors(Cross-Origin Resource Sharing)
                .and().csrf().disable() // close csrf(Cross Site Request Forgery)
                    .authorizeRequests()
                    .antMatchers(ignoreUrls).permitAll() // security white list
                    .antMatchers("/base/**").hasAuthority("admin")
                    .anyRequest().authenticated()//authenticated()//其他请求有认证的用户可以访问
                .and().formLogin() // login default url /api/login #servlet: context-path: /api
                    .successHandler(securityAuthenticationSuccessHandler) // login and return token
                    .failureHandler(securityAuthenticationFailureHandler) // validation while return the wrong message
                .and().logout() // logout default /api/logout #servlet: context-path: /api
                    .logoutSuccessHandler(securityLogoutSuccessHandler)
                .and().sessionManagement() // close session
                    .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and().exceptionHandling() // auth exception handle
                    .accessDeniedHandler(securityAccessDeniedHandler)
                    .authenticationEntryPoint(securityAuthenticationEntryPoint)
                .and().addFilterBefore(jwtAuthenticationTokenFilter(), UsernamePasswordAuthenticationFilter.class); // filter handle token with header
    }

}
